package tetris;

import java.util.HashMap;
import java.util.Map;

public class CharBoard implements Board<String> {

    private boolean[][] dataMap;

    private int rows;
    private int columns;

    private int currentRow = 0;
    private Block currentBlock;

    private Map<Block, Integer> blocksToRows = new HashMap<Block, Integer>();

    public CharBoard(int rows, int columns) {
        this.rows = rows;
        this.columns = columns;

        initDataMap(rows, columns);
    }

    @Override
    public String render() {
        StringBuilder representation = new StringBuilder();

        for (int i = 0; i < rows; i++) {
            String row = renderRow(dataMap[i]);
            representation.append(row);
            if (i < rows - 1) {
                representation.append("\n");
            }
        }

        return representation.toString();
    }

    @Override
    public Boolean hasFallingBlock() {
        return false;
    }

    @Override
    public void drop(Block block) {
        blocksToRows.put(block, 0);
        for (Map.Entry<Block, Integer> entry : blocksToRows.entrySet()) {
            Integer nextBlockRow = entry.getValue();
            dataMap[nextBlockRow][findCenter()] = true;
        }
    }

    @Override
    public void tick() {
        eraseDataMap();

        for (Map.Entry<Block, Integer> entry : blocksToRows.entrySet()) {
            if (entry.getValue() < rows - 1) {
                entry.setValue(entry.getValue() + 1);
            } else {
                drop(new CharBlock('Y'));
            }
        }

        for (Map.Entry<Block, Integer> entry : blocksToRows.entrySet()) {
            dataMap[entry.getValue()][findCenter()] = true;
        }
    }

    private void initDataMap(int rows, int columns) {
        dataMap = new boolean[rows][columns];
    }

    private String renderRow(boolean[] row) {
        StringBuilder representation = new StringBuilder();
        for (boolean rowElement : row) {
            //TODO: Y character should be taken from the appropriate block ...
            representation.append(rowElement ? "Y" : "*");
        }

        return representation.toString();
    }

    private int findCenter() {
        if (columns % 2 == 0) {
            return columns / 2 - 1;
        } else {
            return columns / 2;
        }
    }

    private void eraseDataMap() {
        for (boolean[] rows : dataMap) {
            for (int j = 0; j < rows.length; j++) {
                rows[j] = false;
            }
        }
    }
}
